package csu.big_article.service.Impl;

import csu.big_article.mapper.UserMapper;
import csu.big_article.pojo.User;
import csu.big_article.service.UserService;
import csu.big_article.util.Md5Util;
import csu.big_article.util.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Date;
import java.util.Map;

//将当前类的对象注册到容器里面 IOC的资源复用
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private StringRedisTemplate template;

    @Autowired
    private UserMapper userMapper;

    @Override
    public User findUserById(Integer id) {
        return userMapper.getUserById(id);
    }

    @Override
    public User findUserByName(String name) {
        return userMapper.getUserByName(name);
    }

    @Override
    public void register(String username, String password) {


        //加密
        if (username == null || password == null) {
            System.out.println("username:" + username + "\n" + " password:" + password);
        }else {
            String md5password = Md5Util.getMD5String(password);
            userMapper.register(username,md5password);
        }

    }

    @Override
    public void update(User user) {
        user.setUpdateTime(LocalDateTime.now());
        userMapper.update(user);
    }

    @Override
    public void updateAvatar(String avatarUrl) {
         Map<String,Object> map =ThreadLocalUtil.get();
         Integer id = (Integer) map.get("id");
         LocalDateTime updateTime = LocalDateTime.now();
         Date time = new Date();
         
        userMapper.updateAvatar(avatarUrl,id,updateTime);
    }

    @Override
    public void updatePwd(String newPwd) {
        //将新密码进行编码
        String pwd = Md5Util.getMD5String(newPwd);
        //获取用户的id
        Map<String,Object> map =ThreadLocalUtil.get();
        Integer id = (Integer) map.get("id");
        //获取当前时间作为更新时间
        LocalDateTime updateTime = LocalDateTime.now();

        //删除redis当中的token信息
        template.opsForValue().getOperations().delete((String) map.get("username"));

        userMapper.updatePwd(pwd,id,updateTime);
    }
}
